import qs from 'qs';

export default (query: Record<string, string | number>) => {
  // const iframe = document.createElement('iframe');
  // iframe.style.display = 'none';
  // document.body.appendChild(iframe);
  // const clearReplace = iframe.contentWindow?.history.replaceState.bind(window.history);
  // document.body.removeChild(iframe);
  const clearReplace = window.history.replaceState.bind(window.history);
  if (!clearReplace) {
    console.warn('replace函数获取异常');
    return;
  }
  const regExp = /\?([^#]+)/;
  const oldQuery = location.href.match(regExp)?.[1];
  const currentQuery = oldQuery && qs.parse(oldQuery);
  const queryString = qs.stringify({ ...currentQuery, ...query });
  let newURL = location.href.replace(location.origin, '');
  if (oldQuery) {
    newURL = newURL.replace(regExp, `?${queryString}`);
  } else {
    newURL += `?${queryString}`;
  }
  clearReplace(null, '', newURL);
};
